from flask import Flask, request, jsonify, send_from_directory, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from werkzeug.utils import secure_filename
import os
import uuid
import datetime

app = Flask(__name__)
CORS(app)

# 配置数据库和上传文件夹
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///images.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['ADMIN_PASSWORD'] = 'admin123'  # 管理员密码，可在.env中配置

# 确保上传文件夹存在
if not os.path.exists(app.config['UPLOAD_FOLDER']):
    os.makedirs(app.config['UPLOAD_FOLDER'])

db = SQLAlchemy(app)

# 图片模型
class Image(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    filename = db.Column(db.String(100), nullable=False)
    original_name = db.Column(db.String(100), nullable=False)
    upload_date = db.Column(db.DateTime, default=datetime.datetime.utcnow)
    is_public = db.Column(db.Boolean, default=True)

# 创建数据库表
with app.app_context():
    db.create_all()

# 管理员认证装饰器 - 修改此处以确保端点名称唯一
def admin_required(f):
    def decorated_function(*args, **kwargs):
        password = request.headers.get('Admin-Password')
        if password != app.config['ADMIN_PASSWORD']:
            return jsonify({'error': 'Unauthorized'}), 401
        return f(*args, **kwargs)
    
    # 设置唯一的端点名称
    decorated_function.__name__ = f.__name__ + '_admin_required'
    return decorated_function

# 上传图片
@app.route('/api/admin/upload', methods=['POST'])
@admin_required
def upload_image():
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'}), 400
    
    file = request.files['file']
    
    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400
    
    if file:
        # 生成唯一文件名
        filename = secure_filename(str(uuid.uuid4()) + '_' + file.filename)
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(file_path)
        
        # 保存图片信息到数据库
        image = Image(
            filename=filename,
            original_name=file.filename
        )
        db.session.add(image)
        db.session.commit()
        
        return jsonify({
            'id': image.id,
            'filename': filename,
            'original_name': file.filename,
            'upload_date': image.upload_date.strftime('%Y-%m-%d %H:%M:%S'),
            'url': f'/api/images/{filename}'
        }), 201

# 获取图片列表
@app.route('/api/images', methods=['GET'])
def get_images():
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 12, type=int)
    
    images = Image.query.order_by(Image.upload_date.desc()).paginate(
        page=page, per_page=per_page, error_out=False
    )
    
    result = []
    for image in images.items:
        result.append({
            'id': image.id,
            'filename': image.filename,
            'original_name': image.original_name,
            'upload_date': image.upload_date.strftime('%Y-%m-%d %H:%M:%S'),
            'url': f'/api/images/{image.filename}',
            'is_public': image.is_public
        })
    
    return jsonify({
        'items': result,
        'total_pages': images.pages,
        'total_items': images.total
    })

# 获取单张图片
@app.route('/api/images/<filename>', methods=['GET'])
def get_image(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

# 删除图片
@app.route('/api/admin/images/<int:id>', methods=['DELETE'])
@admin_required
def delete_image(id):
    image = Image.query.get_or_404(id)
    
    # 删除文件
    file_path = os.path.join(app.config['UPLOAD_FOLDER'], image.filename)
    if os.path.exists(file_path):
        os.remove(file_path)
    
    # 从数据库中删除记录
    db.session.delete(image)
    db.session.commit()
    
    return jsonify({'message': 'Image deleted successfully'})

# 切换图片公开状态
@app.route('/api/admin/images/<int:id>/public', methods=['PUT'])
@admin_required
def toggle_public_status(id):
    image = Image.query.get_or_404(id)
    image.is_public = not image.is_public
    db.session.commit()
    
    return jsonify({'message': 'Image status updated successfully', 'is_public': image.is_public})

# 管理员登录
@app.route('/api/admin/login', methods=['POST'])
def admin_login():
    data = request.get_json()
    if not data or 'password' not in data:
        return jsonify({'error': 'Missing password'}), 400
    
    if data['password'] == app.config['ADMIN_PASSWORD']:
        return jsonify({'message': 'Login successful'}), 200
    else:
        return jsonify({'error': 'Invalid password'}), 401

# 首页
@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)